<template>
	<div></div>
</template>

<script>
	import echarts from 'echarts'
	// import 'echarts-gl'
	import 'echarts/theme/dark.js'
	import 'echarts/theme/infographic.js'
	import 'echarts/theme/macarons.js'
	import 'echarts/theme/roma.js'
	import 'echarts/theme/shine.js'
	import 'echarts/theme/vintage.js'
	// import './theme/westeros.js'

	export default {
		name   : "WECharts",
		props  : {
			options: {
				type    : Object,
				required: true
			},
			theme  : {
				type   : String,
				default: 'macarons'
			}
		},
		data() {
			return {
				myChart: null
			}
		},
		watch  : {
			options: {
				deep     : true,
				immediate: true,
				handler(newVal, oldVal) {
					console.log('watch触发->', '新数据', newVal, '旧数据', oldVal);
					this.buildChart(newVal)
				}
			}
		},
		methods: {
			initChart() {
				// 为了防止重复, 先做一次销毁处理
				this.dispose()

				// 基于准备好的dom，初始化echarts实例
				this.myChart = echarts.init(this.$el, this.theme);


				// // 事件部分
				// this.myChart.on('finished', () => {
				// 	console.log('finished');
				// 	this.$emit('finished', this.options)
				// });
			},
			buildChart(newOptions) {
				if (!newOptions || typeof newOptions !== 'object' || this.isEmptyObject(newOptions)) return;

				// console.log('WECharts.vue before nextTick', this.$el, newOptions);
				this.$nextTick(() => {
					// console.log('WECharts.vue after nextTick', this.$el, newOptions);

					// 使用刚指定的配置项和数据显示图表。
					this.myChart.setOption(newOptions, {
						notMerge  : true,
						lazyUpdate: false,
						silent    : false
					});

					//
					this.$nextTick(() => {
						setTimeout(() => {
							this.$emit('set-option', newOptions)
						})
					})

				})

			},
			dispose() {
				if (this.myChart) {
					this.myChart.dispose();
					this.myChart = null;
				}
			},
			isEmptyObject(o) {
				let i;
				for (i in o) return !1;
				return !0
			},
		},
		mounted() {
			this.initChart()
		},
		beforeDestroy() {
			this.dispose()
		},
	}
</script>
